package com.zhou;

import java.awt.Color;
import java.awt.Font;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.JOptionPane;
import javax.swing.UIManager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By.ByCssSelector;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.zhou3.MyForm;

/**
 * 1.设置存储表名 2.设置启用代理 3.设置代理IP和端口
 * 
 * @author zhouweixin
 * 
 */
public class Spider {

	// private static String proxyIpAndPort = "122.72.18.34:80";// 最好用的代理IP
	// proxyIpAndPort = "210.5.149.43:8090";// 下载了1000页
	// 59.67.152.230:3128//下载了1000页
	// 166.111.80.162:3128//下载
	// 120.26.14.14:3128//下载

	// private static String proxyIpAndPort = "110.73.50.196:8123";

	enum Field {
		INVENTOR_NAME(0, "发明名称"), PROXY(1, "代理人"), APPLICANT_NUM(2, "申请号"), APPLICANT_DAY(
				3, "申请日"), PUBLIC_NUM(4, "公开（公告）号"), PUBLIC_DAY(5, "公开（公告）日"), IPC(
				6, "IPC分类号"), ECLA(7, "ECLA分类号"), APPLICANT(8, "申请（专利权）人"), INVENTOR(
				9, "发明人"), PRIORITY_NUM(10, "优先权号"), PRIORITY_DAY(11, "优先权日"), CPC(
				12, "CPC分类号"), C_SETS(13, "C-SETS"), SUMMARY(14, "摘要");

		private final int index;
		private final String name;

		private Field(int index, String name) {
			this.index = index;
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public String getName() {
			return name;
		}
	}

	public static MyForm myForm = null;

	public static WebDriver driver = null;
	public static ChromeOptions options = null;
	public static WebElement captchaElement = null;
	public static WebElement loginElement = null;
	public static Set<Cookie> cookies = null;
	public static String firstHandle = "";
	public static String secondHandle = "";
	public static String thirdHandle = "";
	// 用于存放窗口句柄
	public static Set<String> handleSet = null;

	public static Set<String> patentNumSet = null;

	public static void main(String[] args) {
		Spider spider = new Spider();
	}

	public Spider() {
		System.setProperty("webdriver.chrome.driver", "chromedriver.exe");

		// proxyIpAndPort = "139.217.24.50:3128";
		// proxyIpAndPort = "47.52.44.31:8080";// 可用
		// proxyIpAndPort = "200.174.85.195:3128";// 可用

		/*
		 * 114.215.127.194:3128
		 * 
		 * 139.217.24.50:3128 114.215.95.188:3128 116.62.134.158:3128
		 * 121.196.211.154:3128 202.116.160.104:3128 120.77.254.116:3128
		 */

		// 下面是获得代理的ip
		// Connection connect = Jsoup
		// .connect("http://tvp.daxiangdaili.com/ip/?tid=556416834846055&num=1&ports=80&delay=2&sortby=speed");
		// try {
		// Document document = connect.get();
		//
		// String text = document.text();
		//
		// System.out.println("代理ip=" + text);
		// proxyIpAndPort = text;
		//
		// } catch (IOException e) {
		// e.printStackTrace();
		// }

		// MyAccessDataBase.addIP(proxyIpAndPort);

		// 配置http、ftp、ssl代理（注：当前版本只支持所有的协议公用http协议，下述代码等同于只配置http）
		// Proxy proxy = new Proxy();
		// proxy.setHttpProxy(proxyIpAndPort).setFtpProxy(proxyIpAndPort)
		// .setSslProxy(proxyIpAndPort);
		//
		// options = new ChromeOptions();
		// options.addArguments("--start-maximized");
		// // options.setProxy(proxy);
		// options.setProxy(null);

		// // 以下三行是为了避免localhost和selenium driver的也使用代理，务必要加，否则无法与iedriver通讯
		// DesiredCapabilities cap = new DesiredCapabilities();
		// cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY,
		// true);
		// cap.setCapability(
		// CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC,
		// true);
		// cap.setCapability(ChromeOptions.CAPABILITY, options);
		// System.setProperty("http.nonProxyHosts", "localhost");

		options = new ChromeOptions();
		options.addArguments("--start-maximized");

		// 把窗体设置成统一的字体
		Font font = new Font("Dialog", Font.BOLD, 16);
		UIManager.put("Button.font", font);
		UIManager.put("Label.font", font);
		UIManager.put("Button.font", font);
		UIManager.put("TextField.font", font);

		// 创建窗体
		myForm = new MyForm();
	}

	public static void setProxy(String ipAndPort) {
		Proxy proxy = new Proxy();
		proxy.setHttpProxy(ipAndPort).setFtpProxy(ipAndPort)
				.setSslProxy(ipAndPort);

		options.setProxy(proxy);
		System.out.println(ipAndPort);
	}

	/**
	 * 打开登录页
	 * 
	 * @param loginUrl
	 * @param username
	 * @param password
	 */
	public static void login(String loginUrl, String username, String password) {

		if (myForm.proxyJCheckBox.isSelected()) {
			setProxy(myForm.proxyIPAndPort.getText());
		}

		handleSet = new HashSet<String>();

		options.setHeadless(false);
		options.setBinary("");

		try {
			driver = new ChromeDriver(options);
		} catch (Exception exception) {
			String message = "在路径【"
					+ Spider.class.getResource(".").toString().substring(6)
					+ "】里\n" + "未发现：【lib/chromedriver.exe】\n请解决！";
			JOptionPane.showMessageDialog(myForm, message);
			return;
		}

		if (driver == null) {
			System.out.println("驱动加载失败！");
			return;
		}

		// 加载登录界面
		driver.get(loginUrl);

		delay(100);

		// 获得登录窗口
		WebElement usernameElement = driver.findElement(By.id("j_username"));
		WebElement passwordElement = driver.findElement(By
				.id("j_password_show"));
		captchaElement = driver.findElement(By.id("j_validation_code"));
		WebElement rememberPassword = driver.findElement(By
				.id("wee_remember_me"));
		loginElement = driver.findElement(new ByCssSelector(
				"[class='btn btn-login']"));

		// 写入数据
		usernameElement.clear();
		usernameElement.sendKeys(username);
		delay(200);
		passwordElement.clear();
		passwordElement.sendKeys(password);
		delay(200);
		rememberPassword.click();
	}

	public static boolean inputCaptcha(String captcha) {
		try {
			captchaElement.clear();
			captchaElement.sendKeys(captcha);

			// 登录
			loginElement.click();

			try {
				new WebDriverWait(driver, 20)
						.until(new ExpectedCondition<Boolean>() {
							public Boolean apply(WebDriver driver) {
								return driver.getPageSource().contains("欢迎访问！");
							}
						});
			} catch (Exception exception) {
				System.out.println("登录失败");
				return false;
			}
			cookies = driver.manage().getCookies();

		} catch (Exception e) {
			return false;
		}

		return true;
	}

	public static String readDataFromDB(String url, String tableName,
			String fieldName) {
		try {
			MyAccessDataBase.connectDataBase(url);
		} catch (Exception e) {
			e.printStackTrace();
			return "读取失败";
		}

		patentNumSet = MyAccessDataBase.getPatentNum(tableName, fieldName);
		MyAccessDataBase.closeConnection();
		if (patentNumSet != null && patentNumSet.size() > 0) {
			return "不重复数据共有：" + patentNumSet.size();
		}

		return "读取失败";
	}

	/**
	 * 点击高级检索
	 * 
	 * @param noVisible
	 * @param keyword
	 * @return
	 */
	public static boolean advanceSearch(boolean noVisible, final String keyword) {

		// 设置无头浏览器
		if (noVisible) {
			driver.quit();
			options = new ChromeOptions();

			// 最大化
			options.addArguments("--start-maximized");

			// 无头
			options.setHeadless(true);
			driver = new ChromeDriver(options);

			// 访问地址
			driver.get("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/tableSearch-showTableSearchIndex.shtml");

			driver.manage().deleteAllCookies();
			for (Cookie cookie : cookies) {
				driver.manage().addCookie(cookie);
			}
		}

		// 加载药物检索
		driver.get("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/medicineSearch-initMedicineSearch.shtml");

		// 判断登录成功
		try {
			new WebDriverWait(driver, 10)
					.until(new ExpectedCondition<Boolean>() {
						public Boolean apply(WebDriver driver) {
							return driver.getPageSource().contains("欢迎访问！");
						}
					});
			System.out.println("登录成功!");
		} catch (Exception exception) {
			System.out.println("登录失败");
			JOptionPane.showMessageDialog(myForm, "检索失败，请重试或重新操作！");
			return false;
		}

		// 滚动到页面底下
		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");

		delay(500);
		// 输入检索式
		WebElement searchExpDisplay = driver.findElement(By
				.cssSelector("#searchExpDisplay"));
		searchExpDisplay.sendKeys(keyword);

		delay(1000);

		int times = 10;
		while (true) {
			try {
				// 点击检索
				WebElement med_search_btn = driver.findElement(By
						.cssSelector("#med_search_btn"));
				med_search_btn.click();
				break;
			} catch (Exception e) {
				System.err.println(e.getMessage());
				delay(200);
			}
			times--;
			if (times < 0) {
				return false;
			}
		}

		// 等待加载
		delay(3000);

		// 滚动到页面底下
		jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");

		String pageSource = driver.getPageSource();
		try {
			// 解决&nbsp;乱码的问题
			pageSource = new String(pageSource.getBytes(), "GBK").replace("?",
					"");
		} catch (UnsupportedEncodingException e) {
		}
		Document doc = Jsoup.parse(pageSource);

		String page = doc.select("div.page_bottom > p").get(0).text();
		myForm.sumPageLabel.setText(page);
		myForm.sumPageLabel.setForeground(Color.red);
		myForm.endPageField.setText(page.replace("共", "").replace("页", "")
				.trim());

		return true;
	}

	/**
	 * 开始下载药物数据
	 * 
	 * @param startPage
	 * @param endPage
	 */
	public static void download(final String startPage, final String endPage) {

		if (driver == null) {
			return;
		}

		new Thread(new Runnable() {
			public void run() {

				myForm.downloadButton.setEnabled(false);

				int start = Integer.parseInt(startPage);
				int end = Integer.parseInt(endPage);

				if (start > end) {
					return;
				}

				if (start < 1) {
					start = 1;
				}

				// 每次最多下载的页数
				int maxDownloadPer = 1000;

				JavascriptExecutor jse = (JavascriptExecutor) driver;
				int result = 0;
				myForm.downloadProgressBar.setMaximum(end);
				// 这里同时设置每次最多下载1000页
				for (int i = start; i <= end; i++) {
					myForm.startPageField.setText("" + i);

					int curNum = (i - 1) * 10;

					jse.executeScript("gotoPage('resultlistForm_top', "
							+ curNum + ",true,'search_result');");

					delay(5000);

					jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
					// 判断是否成功

					result = saveDrugPatent(i);

					if (result == 0) {
						i--;
						delay(10000);
					} else if (result < 0) {
						break;
					} else {
						int res = MyAccessDataBase.updateDownloadPage(i);

						if (res < 0) {
							JOptionPane.showMessageDialog(myForm,
									"请设置【起始页】后重新【开始下载】！");
							break;
						} else {
							myForm.downloadProgressBar.setValue(i);
							myForm.nowDownloadPageJLabel.setText(i - start + 1
									+ "");
							myForm.downloadedJLabel.setText(i + " / " + end);
						}
					}

					if (myForm.isStopDownload) {
						break;
					}

					if (i >= start + maxDownloadPer) {
						// 达到每次下载的上限
						JOptionPane.showMessageDialog(myForm, "本次下载达到了 "
								+ maxDownloadPer + " 页, 请稍候下载, 避免IP地址被封");
						break;
					}

					if (i >= end) {
						// 下载完成
						JOptionPane.showMessageDialog(myForm, "下载完成！");
						break;
					}
				}

				myForm.downloadButton.setEnabled(true);
			}
		}).start();

	}

	/**
	 * 保存药物数据
	 */
	public static int saveDrugPatent(int curPage) {

		String pageSource = driver.getPageSource();
		try {
			pageSource = new String(pageSource.getBytes(), "GBK").replace("?",
					"");
		} catch (UnsupportedEncodingException e) {
		}
		Document document = Jsoup.parse(pageSource);

		try {
			if (pageSource.contains("您的操作太过频繁")) {
				// 操作频繁,退出
				JOptionPane.showMessageDialog(null, "操作太过频繁,请稍后重试!");
				return -1;
			}

			// 判断页面跳转是否成功
			String pageString = document.select("div.input_bottom > input#txt")
					.get(0).attr("value");
			if (!pageString.equals(curPage + "")) {
				return 0;
			}
		} catch (Exception exception) {
			return 0;
		}

		Elements elements = document.select("div.list-container ul li");

		List<InfoEntity> infoEntityList = new ArrayList<InfoEntity>();
		for (Element element : elements) {
			// 从此处开始解析数据,并存储
			InfoEntity infoEntity = new InfoEntity();

			// 1.标题
			Elements titleElements = element.select("div.item-header.clear b");
			if (titleElements != null && titleElements.size() > 0) {
				infoEntity.inventionName = titleElements.get(0).text();
			}

			// 内容
			Elements pElements = element.select("div.item-content.clear p");
			if (pElements != null) {
				for (Element p : pElements) {
					String text = p.text();
					parseText(text, infoEntity);
				}
			}

			if (!infoEntity.applicationNumber.equals("")) {
				infoEntityList.add(infoEntity);
			}
		}
		// 存储
		return MyAccessDataBase.insertInfoList(myForm.saveTableName.getText(),
				infoEntityList);
	}

	/**
	 * 解析药物数据
	 * 
	 * @param text
	 * @param infoEntity
	 */
	public static void parseText(String text, InfoEntity infoEntity) {

		if (text == null || text.equals("")) {
			return;
		}

		String[] fieldName = new String[] { "申请号", "申请日", "申请人", "发明人",
				"公开（公告）号", "公开（公告）日", "IPC主分类号", "IPC副分类号", "药物范畴分类号", "申请人地址",
				"摘要" };

		Map<String, Integer> fieldName2indexMap = new HashMap<String, Integer>();
		for (int i = 0; i < fieldName.length; i++) {
			fieldName2indexMap.put(fieldName[i], i);
		}

		String[] strs = text.split(":");

		if (strs.length < 2) {
			return;
		}

		String key = strs[0].trim();

		if (fieldName2indexMap.containsKey(key)) {
			int index = fieldName2indexMap.get(key);
			switch (index) {
			case 0:
				infoEntity.applicationNumber = strs[1].trim();
				break;
			case 1:
				infoEntity.applicationDate = strs[1].trim();
				break;
			case 2:
				infoEntity.applicant = strs[1].trim();
				break;
			case 3:
				infoEntity.inventor = strs[1].trim();
				break;
			case 4:
				infoEntity.publicAnnouncementNumber = strs[1].trim();
				break;
			case 5:
				infoEntity.publicAnnouncementDay = strs[1].trim();
				break;
			case 6:
				infoEntity.mainCategoryIPC = strs[1].trim();
				break;
			case 7:
				infoEntity.subCategoryIPC = strs[1].trim();
				break;
			case 8:
				infoEntity.drugCategoryDOI = strs[1].trim();
				break;
			case 9:
				infoEntity.applicantAddress = strs[1].trim();
				break;
			case 10:
				infoEntity.summary = strs[1].trim();
				break;
			}
		}
	}

	// /**
	// * 下载线程
	// */
	// public static void downloadThread() {
	// // 取出专利号
	// String[] patentNumStrings = patentNumSet.toArray(new String[1]);
	// // 排序
	// Arrays.sort(patentNumStrings);
	//
	// // 设置下载进度条的最大值
	// myForm.downloadProgressBar.setMaximum(patentNumStrings.length - 1);
	//
	// // 开始逐个下载 patentNumStrings.length;
	// for (int index = 58; index < 59; index++) {
	//
	// // 设置进度条
	// myForm.downloadProgressBar.setValue(index);
	// myForm.downloadedJLabel.setText(index + " / "
	// + patentNumStrings.length);
	//
	// // 取出专利号
	// String patentNum = patentNumStrings[index];
	//
	// // 判断是否需要下载
	// String status = MyAccessDataBase.getStatusByPatentStatus(patentNum);
	//
	// // 已下载
	// if (status == null) {
	//
	// } else if (status.equals(Status.DOWNLOADED.getValue())) {
	// continue;
	// }// 格式错误或没有检索到
	// else if (status.equals(Status.FORMAT_ERROR.getValue())
	// || status.equals(Status.NO_SEARCH.getValue())) {
	// continue;
	// }
	// // 存储失败
	// else if (status.equals(Status.SAVE_FAIL.getValue())) {
	// System.out.println(patentNum + ":存储失败");
	// }
	//
	// // 包装成检索式:申复合号码=(US7091236)
	// String searchString = "复合号码=(US" + patentNum + ")";
	// myForm.searchField.setText(searchString);
	//
	// delay(1000);
	//
	// // 输入检索式
	// WebElement searchExpDisplay = driver.findElement(By
	// .cssSelector("#searchExpDisplay"));
	// searchExpDisplay.clear();
	// searchExpDisplay.sendKeys(searchString);
	//
	// int times = 0;
	// while (true) {
	// try {
	// // 点击检索按钮
	// WebElement searchElement = driver
	// .findElement(By
	// .cssSelector("div.box-content-bottom > a.btn.btn-search"));
	// searchElement.click();
	// break;
	// } catch (Exception exception) {
	// times++;
	// if (times > 3) {
	// break;
	// }
	// delay(200);
	// }
	// }
	//
	// // 跳过
	// if (times > 3) {
	// System.out.println(patentNum + ":跳过");
	// continue;
	// }
	//
	// // 等待5秒:一方面是加载,另一方面是减慢操作速度,避免封IP
	// delay(5000);
	// JavascriptExecutor jse = (JavascriptExecutor) driver;
	//
	// // 滚动到页面底
	// jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
	//
	// String html = driver.getPageSource();
	//
	// if (html.contains("没有检索到")) {
	// MyAccessDataBase.updateDownloadPatent(
	// myForm.tableNameJTextField.getText(), patentNum,
	// Status.NO_SEARCH.getValue());
	// System.out.println(patentNum + ":没有检索到");
	// continue;
	// } else if (html.contains("格式错误")) {
	// MyAccessDataBase.updateDownloadPatent(
	// myForm.tableNameJTextField.getText(), patentNum,
	// Status.FORMAT_ERROR.getValue());
	// System.out.println(patentNum + ":格式错误");
	// continue;
	// }
	//
	// // 取出第一个页面的数据
	// String[] data = new String[15];
	// parseFirstPage(html, data);
	//
	// times = 0;
	// while (true) {
	// try {
	// // 跳转到第二个页面
	// WebElement detailElement = driver.findElement(By
	// .linkText("详览"));
	// detailElement.click();
	// break;
	// } catch (Exception exception) {
	// times++;
	// if (times > 3) {
	// break;
	// }
	// delay(200);
	// }
	// }
	//
	// if (times > 3) {
	// System.out.println(patentNum + ":跳过");
	// continue;
	// }
	//
	// delay(5000);
	//
	// // 当前窗口
	// String curHandle = driver.getWindowHandle();
	// String secondHandle = null;
	// Set<String> handles = driver.getWindowHandles();
	// for (String handle : handles) {
	// if (!handle.equals(curHandle)) {
	// secondHandle = handle;
	// break;
	// }
	// }
	//
	// if (secondHandle == null) {
	// continue;
	// }
	//
	// // 切换到第二页面
	// WebDriver sencodeDriver = driver.switchTo().window(secondHandle);
	//
	// // 滚动到页面底
	// jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
	//
	// delay(1000);
	//
	// html = driver.getPageSource();
	//
	// // 解析第二页面
	// parseSecondPage(html, data);
	//
	// boolean b = MyAccessDataBase.addData(data);
	//
	// if (b) {
	// MyAccessDataBase.updateDownloadPatent(
	// myForm.tableNameJTextField.getText(), patentNum,
	// Status.DOWNLOADED.getValue());
	// System.out.println(patentNum + ":保存成功");
	// } else {
	// MyAccessDataBase.updateDownloadPatent(
	// myForm.tableNameJTextField.getText(), patentNum,
	// Status.SAVE_FAIL.getValue());
	// System.out.println(patentNum + ":保存失败");
	// }
	//
	// // // 关闭子窗口
	// // sencodeDriver.close();
	// // // 切换回父窗口
	// // driver.switchTo().window(curHandle);
	// }
	// }

	/**
	 * 解析第二页面
	 * 
	 * @param html
	 * @param data
	 */
	public static void parseSecondPage(String html, String[] data) {
		// 解决乱码
		try {
			html = new String(html.getBytes(), "GBK").replace('?', ' ')
					.replace('　', ' ');
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Document document = Jsoup.parse(html);
		Element element = document.select(
				"div#tabContent_1_id div.tabContent_1_content").get(0);
		String title = element.select("div.table-container-title").get(0)
				.text();
		Elements trs = element.select("div.table-container table tbody tr");

		setDataValueByFieldName(title, data);

		for (Element tr : trs) {
			setDataValueByFieldName(tr.text(), data);
		}

	}

	/**
	 * 解析第一页面
	 * 
	 * @param html
	 * @param data
	 */
	public static void parseFirstPage(String html, String[] data) {
		// 解决乱码
		try {
			html = new String(html.getBytes(), "GBK").replace('?', ' ')
					.replace('　', ' ');
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Document document = Jsoup.parse(html);
		Elements elements = document
				.select("div#search_result div.list-container li.patent div.item");

		// 这里只取一个
		if (elements != null) {
			Element element = elements.get(0);
			Elements ps = element
					.select("div.item-content.clear div.item-content-body.left p");

			for (Element p : ps) {
				setDataValueByFieldName(p.text(), data);
			}
		}

	}

	/**
	 * 通过字段名获得字段值
	 * 
	 * @param string
	 * @return
	 */
	public static void setDataValueByFieldName(String string, String[] data) {
		for (Field field : Field.values()) {
			if (string.startsWith(field.getName())) {
				data[field.getIndex()] = string.replace(field.getName(), "")
						.replace(":", "").replace("---", "").trim();
			}
		}
	}

	/**
	 * 保存数据
	 */
	public static void saveData(String html) {
		//
		// List<WebElement> webElementList = driver
		// .findElements(By
		// .cssSelector("#search_result > div.re-content.search-mode-content > div.list-container > ul > li"));
		//
		// for (WebElement webElement : webElementList) {
		// // 新建数据对象
		// Data data = new Data();
		//
		// try {
		// data.name = webElement
		// .findElement(
		// By.cssSelector("div.item div.item-header.clear > h1 > div:nth-child(2)"))
		// .getText();
		// } catch (Exception e) {
		// String textString = webElement
		// .findElement(
		// By.cssSelector("div.item > div.item-header.clear > h1 > span"))
		// .getText();
		// if (textString.contains("无标题")) {
		// break;
		// }
		// e.printStackTrace();
		// }
		//
		// // 代理人
		// List<WebElement> pList = webElement.findElements(By
		// .cssSelector("p"));
		// String proxyString = pList.get(pList.size() - 1).getText();
		//
		// // 代理人
		// if (proxyString.startsWith("代理人 :")) {
		// data.proxy = proxyString.replace("代理人 :", "").trim();
		// }
		//
		// // 点击详览
		// int times = 0;
		// while (true) {
		// try {
		// WebElement detailElement = webElement.findElement(By
		// .linkText("详览"));
		// // detailElement.click();
		// Actions action = new Actions(driver);
		// action.click(detailElement).perform();
		// break;
		// } catch (Exception e) {
		// e.printStackTrace();
		// times++;
		// System.out.println(times);
		// if (times > 0) {
		// break;
		// }
		// }
		// }
		//
		// // 当前窗口
		// String curHandle = driver.getWindowHandle();
		// String secondHandle = "";
		// Set<String> handles = driver.getWindowHandles();
		// for (String handle : handles) {
		// if (!handle.equals(curHandle)) {
		// secondHandle = handle;
		//
		// // 切换到第二页面
		// WebDriver sencodeDriver = driver.switchTo().window(
		// secondHandle);
		//
		// // 滚动到页面底下
		// jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
		//
		// List<WebElement> elements = null;
		// try {
		// // 取表格中的内容
		// new WebDriverWait(driver, 20)
		// .until(ExpectedConditions.presenceOfElementLocated(By
		// .cssSelector("div.table-container > table > tbody > tr")));
		// elements = driver
		// .findElements(By
		// .cssSelector("div.table-container > table > tbody > tr"));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//
		// if (elements != null) {
		// for (WebElement element : elements) {
		// String text = element.findElement(
		// By.cssSelector("td.first-td > div"))
		// .getText();
		//
		// if (text.contains("申请号")) {
		// data.applicantNum = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("申请日")) {
		// data.applicantDay = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("公开（公告）号")) {
		// data.publicNum = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("公开（公告）日")) {
		// data.publicDay = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("IPC分类号")) {
		// data.ipc = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("ECLA分类号")) {
		// data.ecla = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("申请（专利权）人")) {
		// data.applicant = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("发明人")) {
		// data.inventor = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("优先权号")) {
		// data.priorityNum = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("优先权日")) {
		// data.priorityDay = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("CPC分类号")) {
		// data.cpc = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// } else if (text.contains("C-SETS")) {
		// data.csets = element.findElement(
		// By.cssSelector("td.second-td > div"))
		// .getText();
		// }
		// }
		// }
		//
		// try {
		// // 摘要
		// data.summary = driver.findElement(
		// By.cssSelector("#sipoabs_content_0 > p"))
		// .getText();
		// } catch (Exception e) {
		// System.out.println("摘要查询出错");
		// }
		//
		// // System.out.println(data.toString());
		//
		// // 保存数据
		// boolean b = MyAccessDataBase.addData(data);
		// if (b) {
		// MyAccessDataBase.updateDownloadPatent(
		// myForm.tableNameJTextField.getText(),
		// patentNum, Status.DOWNLOADED.getValue());
		// } else {
		// MyAccessDataBase.updateDownloadPatent(
		// myForm.tableNameJTextField.getText(),
		// patentNum, Status.SAVE_FAIL.getValue());
		// System.out.println(patentNum + ":保存失败");
		// }
		// // 关闭子窗口
		// sencodeDriver.close();
		// // 切换回父窗口
		// driver.switchTo().window(curHandle);
		// break;
		// }
		// }
		// }
	}

	/**
	 * 点击药物检索
	 * 
	 * @param noVisible
	 * @param keyword
	 * @return
	 */
	public static int search(boolean noVisible, String keyword) {

		if (noVisible) {
			driver.quit();
			options = new ChromeOptions();
			options.addArguments("--start-maximized");
			options.addArguments("headless");
//			options.setHeadless(true);
			driver = new ChromeDriver(options);
			driver.get("http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml");

			delay(5000);

			driver.manage().deleteAllCookies();
			for (Cookie cookie : cookies) {
				driver.manage().addCookie(cookie);
			}
		}

		driver.get("http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml");

		// 获得[药物检索]按钮,并点击
		WebElement search = null;
		while (true) {
			try {
				search = driver
						.findElement(By
								.cssSelector("div.nav div.nav-wrap.clear div.nav-items ul.clear li[menuid='ui_medcineSearch'] a"));
				search.click();
				break;
			} catch (Exception e) {
				delay(100);
			}
		}

		delay(5000);

		// 当前窗口句柄
		firstHandle = driver.getWindowHandle();
		handleSet.add(firstHandle);
		// 新窗口句柄
		secondHandle = firstHandle;

		// 获得所有窗口句柄
		Set<String> handles = driver.getWindowHandles();
		Iterator it = handles.iterator();
		while (it.hasNext()) {
			secondHandle = (String) it.next();
			// 寻找新增的窗口句柄
			if (!handleSet.contains(secondHandle)) {
				handleSet.add(secondHandle);
				break;
			}
		}

		// 切换到新窗口
		driver.switchTo().window(secondHandle);

		// 申请日=19850910:20171229
		while (true) {
			try {
				driver.switchTo().window(secondHandle);
				WebElement searchExpDisplay = driver.findElement(By
						.cssSelector("#searchExpDisplay"));
				searchExpDisplay.clear();
				searchExpDisplay.sendKeys(keyword);

				WebElement searchElement = driver.findElement(By
						.cssSelector("#med_search_btn"));
				searchElement.click();
				break;
			} catch (Exception e) {
				delay(100);
				e.printStackTrace();
			}
		}

		delay(5000);
		System.out.println("数据开始加载。。。");

		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
		delay(1000);

		int num_page = 0;
		while (true) {
			try {
				num_page = Integer
						.parseInt(driver
								.findElement(
										By.cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > p:nth-child(6)"))
								.getText().replace("共", "").replace("页", "")
								.trim());
				break;
			} catch (Exception e) {
				delay(100);
				e.printStackTrace();
			}
		}

		MyAccessDataBase.closeConnection();
		System.out.println("共有" + num_page + "页");
		return num_page;
	}

	public static void download(int startPage, int endPage, String tableName) {
		List<InfoEntity> infoEntityList = new ArrayList<InfoEntity>();
		JavascriptExecutor jse = (JavascriptExecutor) driver;

		// 跳转到第startPage页
		while (true) {
			try {
				WebElement gotoPage = driver
						.findElement(By.cssSelector("#txt"));
				WebElement buttonOK = driver
						.findElement(By
								.cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > a:nth-child(10)"));
				gotoPage.clear();
				gotoPage.sendKeys("" + startPage);
				buttonOK.click();
				break;
			} catch (Exception e) {
				delay(100);
				e.printStackTrace();
			}
		}
		// 存储数据
		int i = startPage;
		while (true) {
			System.out.println("==========第" + (i) + "页=============");

			List<WebElement> elementList = driver
					.findElements(By
							.cssSelector("#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li"));
			infoEntityList.clear();

			for (int j = 0; j < elementList.size(); j++) {
				// System.out.println(j);
				InfoEntity infoEntity = new InfoEntity();
				String[] strs = null;
				WebElement element = null;
				String css = "#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li:nth-child("
						+ (j + 1) + ")";
				while (true) {
					try {
						element = driver.findElement(By.cssSelector(css));
						strs = element.getText().split("\n");
						break;
					} catch (Exception e) {
						delay(100);
						e.printStackTrace();
						driver.switchTo().window(secondHandle);
					}
				}
				infoEntity.setAllAttribute(strs);

				// 查看摘要
				WebElement seeDetail = null;
				int times = 0;
				while (true) {
					try {
						times++;
						if (times > 50) {
							break;
						}
						seeDetail = element.findElement(By
								.partialLinkText("查看详细"));
						Actions action = new Actions(driver);
						action.click(seeDetail).perform();
						break;
					} catch (Exception e) {
						delay(500);
						e.printStackTrace();
						element = driver.findElement(By.cssSelector(css));
						driver.switchTo().window(secondHandle);
					}
				}

				Set<String> handles = driver.getWindowHandles();
				Iterator it = handles.iterator();
				while (it.hasNext()) {
					thirdHandle = (String) it.next();
					// 寻找新增的窗口句柄
					if (!handleSet.contains(thirdHandle)) {
						while (true) {
							try {
								driver.switchTo().window(thirdHandle);
								infoEntity
										.setSummary(driver
												.findElement(
														By.cssSelector("#detailViewPanel > table:nth-child(2) > tbody > tr > td"))
												.getText());
								break;
							} catch (Exception e) {
								delay(100);
								e.printStackTrace();
							}
						}
						break;
					}
				}

				// System.out.println(infoEntity);
				infoEntityList.add(infoEntity);
				driver.switchTo().window(secondHandle);
			}

			// 先滚动到页面底下
			jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");

			while (true) {
				try {
					WebElement nextButton = driver.findElement(By
							.linkText("下一页"));
					nextButton.click();
					break;
				} catch (Exception e) {
					delay(100);
				}
			}

			MyAccessDataBase.insertInfoList(tableName, infoEntityList);
			System.out.println("第" + i + "页，成功!");

			i++;
			if (i >= endPage) { // num_page
				break;
			}
		}
	}

	public static void delay(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
